import { createStore } from 'vuex'
import axios from 'axios'

// 后端API基础URL
const API_BASE_URL = `http://${window.location.hostname}:5000/api`

// 从本地存储加载聊天历史
const loadChatsFromStorage = () => {
  try {
    const savedChats = localStorage.getItem('chatHistory');
    return savedChats ? JSON.parse(savedChats) : {};
  } catch (e) {
    console.error('Error loading chats from localStorage:', e);
    return {};
  }
};

// 保存聊天历史到本地存储
const saveChatsToStorage = (chats) => {
  try {
    localStorage.setItem('chatHistory', JSON.stringify(chats));
  } catch (e) {
    console.error('Error saving chats to localStorage:', e);
  }
};

export default createStore({
  state: {
    knowledgeBase: [],
    queryResults: null,
    loading: false,
    error: null,
    llmConfig: null,
    // 聊天历史记录
    chats: loadChatsFromStorage(),
    currentChatId: null
  },
  mutations: {
    setKnowledgeBase(state, data) {
      state.knowledgeBase = data
    },
    setQueryResults(state, data) {
      state.queryResults = data
    },
    setLoading(state, status) {
      state.loading = status
    },
    setError(state, error) {
      state.error = error
    },
    setLLMConfig(state, config) {
      state.llmConfig = config
    },
    // 新增的聊天相关mutations
    setCurrentChatId(state, chatId) {
      state.currentChatId = chatId;
    },
    addChat(state, chat) {
      state.chats[chat.id] = chat;
      saveChatsToStorage(state.chats);
    },
    updateChat(state, { chatId, updates }) {
      if (state.chats[chatId]) {
        state.chats[chatId] = { ...state.chats[chatId], ...updates };
        saveChatsToStorage(state.chats);
      }
    },
    addMessage(state, { chatId, message }) {
      if (state.chats[chatId]) {
        if (!state.chats[chatId].messages) {
          state.chats[chatId].messages = [];
        }
        state.chats[chatId].messages.push(message);
        saveChatsToStorage(state.chats);
      }
    },
    deleteChat(state, chatId) {
      if (state.chats[chatId]) {
        // 使用Vue的响应式删除方法
        const newChats = { ...state.chats };
        delete newChats[chatId];
        state.chats = newChats;
        
        // 如果删除的是当前聊天，清空当前聊天ID
        if (state.currentChatId === chatId) {
          state.currentChatId = null;
        }
        
        saveChatsToStorage(state.chats);
      }
    },
    clearChats(state) {
      state.chats = {};
      state.currentChatId = null;
      saveChatsToStorage(state.chats);
    }
  },
  actions: {
    // 加载知识库
    async fetchKnowledgeBase({ commit }) {
      commit('setLoading', true)
      try {
        const response = await axios.get(`${API_BASE_URL}/knowledge`)
        commit('setKnowledgeBase', response.data)
      } catch (error) {
        commit('setError', '无法加载知识库: ' + error.message)
      } finally {
        commit('setLoading', false)
      }
    },
    
    // 添加知识
    async addKnowledge({ commit, dispatch }, text) {
      commit('setLoading', true)
      try {
        await axios.post(`${API_BASE_URL}/knowledge`, { text })
        // 重新加载知识库
        dispatch('fetchKnowledgeBase')
      } catch (error) {
        commit('setError', '添加知识失败: ' + error.message)
      } finally {
        commit('setLoading', false)
      }
    },
    
    // 查询
    async query({ commit }, { question, topK = 3 }) {
      commit('setLoading', true)
      commit('setQueryResults', null)
      try {
        const response = await axios.post(`${API_BASE_URL}/query`, { 
          question, 
          top_k: topK 
        })
        commit('setQueryResults', response.data)
        return response.data;
      } catch (error) {
        commit('setError', '查询失败: ' + error.message)
        throw error;
      } finally {
        commit('setLoading', false)
      }
    },
    
    // 获取大模型配置
    async fetchLLMConfig({ commit }) {
      commit('setLoading', true)
      try {
        const response = await axios.get(`${API_BASE_URL}/llm/config`)
        commit('setLLMConfig', response.data)
      } catch (error) {
        commit('setError', '获取配置失败: ' + error.message)
      } finally {
        commit('setLoading', false)
      }
    },
    
    // 更新大模型配置
    async updateLLMConfig({ commit, dispatch }, config) {
      commit('setLoading', true)
      try {
        await axios.post(`${API_BASE_URL}/llm/config`, config)
        // 重新获取配置
        dispatch('fetchLLMConfig')
      } catch (error) {
        commit('setError', '更新配置失败: ' + error.message)
      } finally {
        commit('setLoading', false)
      }
    },
    
    // 创建新聊天
    createChat({ commit }) {
      const newId = Date.now().toString();
      const newChat = {
        id: newId,
        title: '新对话',
        createdAt: new Date().toISOString(),
        messages: []
      };
      
      commit('addChat', newChat);
      commit('setCurrentChatId', newId);
      return newId;
    },
    
    // 选择聊天
    selectChat({ commit }, chatId) {
      commit('setCurrentChatId', chatId);
    },
    
    // 删除聊天
    deleteChat({ commit }, chatId) {
      commit('deleteChat', chatId);
    },
    
    // 发送消息并获取回复
    async sendMessage({ commit, state, dispatch }, text) {
      let chatId = state.currentChatId;
      
      // 如果没有当前聊天，创建一个新的
      if (!chatId || !state.chats[chatId]) {
        chatId = await dispatch('createChat');
      }
      
      // 添加用户消息
      const userMessage = {
        role: 'user',
        content: text,
        timestamp: new Date().toISOString()
      };
      commit('addMessage', { chatId, message: userMessage });
      
      try {
        // 调用API获取回答
        const response = await dispatch('query', {
          question: text,
          topK: 3
        });
        
        // 如果是新聊天，更新标题
        if (state.chats[chatId].title === '新对话') {
          // 使用问题的前15个字作为标题
          const newTitle = text.length > 15 
            ? text.substring(0, 15) + '...' 
            : text;
          commit('updateChat', { 
            chatId, 
            updates: { title: newTitle } 
          });
        }
        
        // 添加AI回复
        const aiMessage = {
          role: 'assistant',
          content: response.answer,
          sources: response.retrieved_knowledge,
          timestamp: new Date().toISOString()
        };
        commit('addMessage', { chatId, message: aiMessage });
        
        return response;
      } catch (error) {
        // 添加错误回复
        const errorMessage = {
          role: 'assistant',
          content: '很抱歉，我在处理您的请求时遇到了问题。请稍后再试。',
          timestamp: new Date().toISOString()
        };
        commit('addMessage', { chatId, message: errorMessage });
        throw error;
      }
    }
  },
  getters: {
    getCurrentChat: (state) => {
      return state.currentChatId ? state.chats[state.currentChatId] : null;
    },
    // 按时间倒序排列的聊天列表
    chatHistory: (state) => {
      return Object.values(state.chats)
        .sort((a, b) => {
          // 获取最后一条消息的时间或创建时间
          const aTime = a.messages && a.messages.length > 0 
            ? a.messages[a.messages.length - 1].timestamp 
            : a.createdAt;
          const bTime = b.messages && b.messages.length > 0
            ? b.messages[b.messages.length - 1].timestamp
            : b.createdAt;
          
          // 倒序排列，最新的在前面
          return new Date(bTime) - new Date(aTime);
        });
    }
  }
}) 